package com.xcc.mota.sprite;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;

import com.xcc.mota.utils.Logger;

/**
 * 图片精灵
 * Created by Administrator on 2018/1/8.
 */
public class TextSprite extends BaseSprite {
    private String text;
    private int textColor;
    private int textSize;
    private boolean isBold;
    private float descent;//文字偏移

    public TextSprite setBold(boolean bold) {
        isBold = bold;
        return this;
    }

    public TextSprite setTextSize(int textSize) {
        this.textSize = textSize;
        setRectF(null);
        return this;
    }

    public TextSprite setText(String text) {
        this.text = text;
        setRectF(null);
        return this;
    }

    public TextSprite setTextColor(int textColor) {
        this.textColor = textColor;
        return this;
    }

    public void onDraw(Canvas canvas, Paint paint) {
        paint.setColor(textColor);
        paint.setTextAlign(Paint.Align.CENTER);
        paint.setTextSize(textSize);
        paint.setStrokeWidth(textSize / 20.0f);
        paint.setStyle(isBold ? Paint.Style.FILL_AND_STROKE : Paint.Style.FILL);

        RectF rectF = getRectF();
        if (rectF == null) {
            float textLength = paint.measureText(text) / 2.0f;
            float s = textSize / 2.0f;
            setRectF(new RectF(x - textLength, y - s, x + textLength, y + s));
            Paint.FontMetrics fontMetrics = paint.getFontMetrics();
            descent = (fontMetrics.bottom - fontMetrics.top) / 2 + fontMetrics.top;
        }

        canvas.drawText(text, x, y - descent, paint);

        if (Logger.isDebug) {
            rectF = getRectF();
            paint.setColor(0x33FFFF00);
            canvas.drawRect(rectF.left, rectF.top, rectF.right, rectF.bottom, paint);
        }
    }
}
